﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
    [JwtAuthentication]
    public class UploadImageController : ApiController
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        public class UploadImageClass
        {
            public string Type { get; set; }

            public string ImagePath { get; set; }
        }
        // POST api/<controller>
        public async Task<HttpResponseMessage> Post()
        {
            ReturnObject RO = new ReturnObject();

            if (!Request.Content.IsMimeMultipartContent())
            {
                return Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
            }

            var root = HttpContext.Current.Server.MapPath("~/Uploads");
            Directory.CreateDirectory(root);
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                string RQ = DateTime.Now.Date.ToString("yyyyMMdd");
                await Request.Content.ReadAsMultipartAsync(provider);
                // 获取表单数据中的其他值
                var formData = provider.FormData;
                var customPath = formData["Type"]; // 获取名为 "Type" 的表单值
                Directory.CreateDirectory(Path.Combine(root, RQ, customPath));
                var filePaths = "";

                foreach (var file in provider.FileData)
                {
                    var fileName = Path.GetFileName(file.Headers.ContentDisposition.FileName.Trim('\"'));
                    var localFileName = file.LocalFileName;

                    var filePath = Path.Combine(root, RQ, customPath, fileName);
                  
                    // 构建文件的 HTTP URL
                    
                    File.Move(localFileName, filePath);
                    var filePathnew = $"{Request.RequestUri.Scheme}://{Request.RequestUri.Host}:{Request.RequestUri.Port}/Uploads/{RQ}/{customPath}/{fileName}";
                    filePaths += filePathnew + ";";
                }

                return Request.CreateResponse(HttpStatusCode.OK, new { message = "上传成功", ImageUrl = filePaths });
            }
            catch (Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
        // 密钥和初始化向量
        private static readonly byte[] Key = Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JwtSecret"]);
        private static readonly byte[] IV = Encoding.UTF8.GetBytes("HSY123456789");

        // AES加密函数
        public static string Encrypt(string plainText)
        {
            using (var aes = Aes.Create())
            {
                aes.Key = Key;
                aes.IV = IV;
                var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        using (var sw = new StreamWriter(cs))
                        {
                            sw.Write(plainText);
                        }
                    }
                    return Convert.ToBase64String(ms.ToArray());
                }
            }
        }
    }
}